#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys, os

from loguru import logger

import pandas as pd

from PyQt5.QtWidgets import QApplication, QTableView

from PyQt5.QtCore import QAbstractTableModel, QModelIndex, QVariant, Qt

DATA_PATH = os.getcwd() + "\\data\\metadata.csv"


class  PAIDataRecord(QAbstractTableModel):
    def __init__(self):
        super().__init__()
        self.datapath = DATA_PATH
        self.wholedata = []
        self.displaydata = []
        #print(self.datapath)
        self.load()
        logger.debug("create an instance of PAIDataRecord successfully.")
    
    def load(self):
        self.beginResetModel()
        self.wholedata = pd.read_csv(self.datapath)
        self.displaydata = self.wholedata.iloc[:, :5]
        self.endResetModel()
        logger.debug("load csv file {} successfully.", self.datapath)
    
    # 需实现的接口，返回数据行数
    def rowCount(self, parent = None):
        return self.displaydata.shape[0]

    # 需实现的接口，返回数据列数
    def columnCount(self, parent = None):
        return self.displaydata.shape[1]
    

    def data(self, index, role = Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return str(self.displaydata.iloc[index.row(), index.column()])
        return None
    
    # 需实现标题行的定义
    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.displaydata.columns[col]
        return None
    
    # View中编辑后，View会调用这个方法修改Model中的数据
    def setData(self, index, value, role = Qt.EditRole):
        if index.isValid() and 0 <= index.row() < len(self.displaydata) and value:
            col = index.column()
        pass

    #必须实现的接口，不实现，View中的数据不可编辑
    def flags(self, index):
        if not index.isValid():
            return Qt.ItemIsEnabled
        
        return Qt.ItemFlags(QAbstractTableModel.flags(self, index)|Qt.ItemIsEditable|Qt.ItemIsSelectable)

    def insertRows(self, position, rows=1, index=QModelIndex()):
        return True

    def removeRows(self, position, rows=1, index=QModelIndex):
        return True
    


if __name__ == "__main__":
    # cwdpath = os.getcwd()
    # datapath = cwdpath + "\\data\\metadata.csv"
    # print(datapath)
    # read_file = pd.read_csv(datapath)
    # #read_file = csv.reader()
    # print(type(read_file))
    # print(read_file)

    app = QApplication(sys.argv)
    model = PAIDataRecord()
    #model.load()
    view = QTableView()
    view.setModel(model)
    view.resize(800, 600)
    view.show()
    sys.exit(app.exec_())
